package com.zx.service.user.impl;

import com.zx.config.exception.BaseBusinessException;
import com.zx.config.exception.UserError;
import com.zx.dao.user.UserMapper;
import com.zx.dto.request.user.UserDtoReq;
import com.zx.model.user.User;
import com.zx.service.user.UserService;
import com.zx.util.MD5Util;
import com.zx.util.MallConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper usermapper;

    @Override
    public User login(UserDtoReq dtoReq, HttpServletResponse response) {
        User user = usermapper.login(dtoReq);
        if (ObjectUtils.isEmpty(user)) {
            return user;
        }
        /*用户密码验证*/
        if (MD5Util.verify(dtoReq.getPwd(), user.getSalt(), user.getPassword())) {
            user.setAvatar(avatar + user.getAvatar());
            MallConstant.MAP.put(user.getId().toString(), user);
            Cookie cookie = new Cookie(MallConstant.TOKEN, user.getId().toString());
            cookie.setMaxAge(24 * 60 * 60);
            cookie.setPath("/");
            response.addCookie(cookie);
            return user;
        } else {
            throw new BaseBusinessException(UserError.USER_PASSWORD_ERROR.getErrorCode(), UserError.USER_PASSWORD_ERROR.getErrorMessage());
        }
    }

    @Autowired
    private String avatar;

    public User queryUser(String userToken) {
        User user = MallConstant.MAP.get(userToken);
        return user;
    }

    @Override
    public boolean updataUser(UserDtoReq userDtoReq, String userToken) {
        userDtoReq.setUpdateTime(new Date());
        if (userDtoReq.getPasswrod() != null) {
            User user = MallConstant.MAP.get(userToken);
            boolean verify = MD5Util.verify(userDtoReq.getOriginalPassword(), user.getSalt(), user.getPassword());
            if (verify == true) {
                userDtoReq.setPasswrod(MD5Util.encrypt(userDtoReq.getPasswrod(), user.getSalt()));
                int i = usermapper.updataUser(userDtoReq);
                if (i <= 0) {
                    throw new BaseBusinessException(UserError.USER_PASSWORD_ERROR.getErrorCode(), UserError.USER_PASSWORD_ERROR.getErrorMessage());
                }
                return true;
            }
      /*  int i = usermapper.updataUser(userDtoReq);
        if (i<=0){
            throw new BaseBusinessException("修改失败");
        }*/
        } else {
            int i = usermapper.updataUser(userDtoReq);
            if (i <= 0) {
                throw new BaseBusinessException(UserError.USER_PASSWORD_ERROR.getErrorCode(), UserError.USER_PASSWORD_ERROR.getErrorMessage());
            }
            return true;
        }
        return false;

    }
}
